//  Abstract:
//    See ocf.h
//
//  Reference:
//    See ocf.h
//
//  Design Notes:
//    See ocf.h
//
//  Disclaimer:
//    Copyright (C) 2008, Janice Law <janicel700@gmail.com>.
//
//    This program is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    This program is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
//  Change Log:
//
#include <zip.h>
#include <libxml++/libxml++.h>
#include <boost/shared_ptr.hpp>
#include <boost/scoped_ptr.hpp>
#include "ocf.h"

using namespace boost;
using namespace std;
using Glib::ustring;
using Glib::RefPtr;

namespace Epub
{
Ocf::Ocf()
{
    archive_path = "";
}

Ocf::Ocf(ustring const archivePath)
{
    archive_path = archivePath;
}

Ocf::~Ocf()
{
}

ustring Ocf::get_archive_path()
{
    return archive_path;
}

shared_ptr<xmlpp::Document> Ocf::ReadXML(ustring const fileName)
{
    int zip_errno;
    struct zip* ocf_archive = zip_open(archive_path.c_str(), 0, &zip_errno);
    if (ocf_archive != NULL)
    {
        struct zip_stat xml_file_stat;
        zip_stat(ocf_archive, fileName.c_str(), 0, &xml_file_stat);
        struct zip_file* xml_file = zip_fopen(ocf_archive, fileName.c_str(), 0);
        if (xml_file != NULL)
        {
            unsigned char* buffer =
                    (unsigned char*)std::malloc(xml_file_stat.size);
            if (buffer != NULL)
            {
                try
                {
                    if(zip_fread(xml_file, buffer, xml_file_stat.size) != xml_file_stat.size) throw 0;
                    scoped_ptr<xmlpp::DomParser> parser(new xmlpp::DomParser);
                    parser->set_substitute_entities();
                    parser->parse_memory_raw(buffer, xml_file_stat.size);
                    shared_ptr<xmlpp::Document> document(new xmlpp::Document);
                    document->create_root_node_by_import(parser->get_document()->get_root_node());
                    std::free(buffer);
                    zip_fclose(xml_file);
                    zip_close(ocf_archive);
                    return document;
                }
                catch(...)
                {
                    ; // Ignore exception and return NULL
                }
            }
            std::free(buffer);
        }
        zip_fclose(xml_file);
    }
    zip_close(ocf_archive);
    return shared_ptr<xmlpp::Document>();
}

void Ocf::WriteXML(ustring const fileName, shared_ptr<xmlpp::Document> content)
{
    struct zip_source* source_buffer;
    int zip_errno;
    struct zip* ocf_archive = zip_open(archive_path.c_str(), 0, &zip_errno);
    if (ocf_archive == NULL)
    {
        throw 0;
    }
    int file_index = zip_name_locate(ocf_archive, fileName.c_str(), 0);
    if (file_index == -1)
    {
        throw 0;
    }
    ustring xml_string = content->write_to_string();
    source_buffer = zip_source_buffer(ocf_archive, (void*)xml_string.c_str(),
            xml_string.bytes(), 0);
    if (zip_replace(ocf_archive, file_index, source_buffer) == file_index)
    {
        throw 0;
    }
    zip_close(ocf_archive);
}

void Ocf::WriteOPF(shared_ptr<Opf> content)
{
    typedef std::pair<Glib::ustring, Glib::ustring> nsPair;
    shared_ptr<xmlpp::Document> container_xml(ReadXML("META-INF/container.xml"));
    xmlpp::Node::PrefixNsMap nsMap;
    nsMap.insert(nsPair("epub",
            "urn:oasis:names:tc:opendocument:xmlns:container"));
    ustring
            xpath =
                    "/epub:container/epub:rootfiles/epub:rootfile \
                    [@media-type='application/oebps-package+xml']";
    xmlpp::NodeSet result = container_xml->get_root_node()->find(xpath, nsMap);
    if (result.empty())
        throw 0;
    ustring opf_path = dynamic_cast<xmlpp::Element*>(result[0])->get_attribute_value("full-path");
    content->opf_xml->get_root_node()->set_namespace(""); // Workaround: Strip forced namespace for libxml
    WriteXML(opf_path, content->opf_xml);
    content->opf_xml->get_root_node()->set_namespace("opf"); // Workaround: Forced namespace for libxml
}

shared_ptr<Opf> Ocf::ReadOPF()
{
    typedef std::pair<Glib::ustring, Glib::ustring> nsPair;
    shared_ptr<xmlpp::Document> container_xml(ReadXML("META-INF/container.xml"));
    xmlpp::Node::PrefixNsMap nsMap;
    nsMap.insert(nsPair("epub",
            "urn:oasis:names:tc:opendocument:xmlns:container"));
    ustring
            xpath =
                    "/epub:container/epub:rootfiles/epub:rootfile \
                    [@media-type='application/oebps-package+xml']";
    xmlpp::NodeSet result = container_xml->get_root_node()->find(xpath, nsMap);
    if (result.empty())
        return shared_ptr<Opf>();
    ustring opf_path = dynamic_cast<xmlpp::Element*>(result[0])->get_attribute_value("full-path");
    shared_ptr<Opf> return_val(new Opf(ReadXML(opf_path)));
    return return_val;
}
} // Epub
